package com.example.admin.goodnews.choosecity;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.example.admin.goodnews.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * 将assets下的数据库文件里的内容复制到包名下
 * Created by admin on 2016/10/12.
 */

public class DBManager {
    private String DB_NAME = "allcity.db";
    private Context mContext;

    public DBManager(Context mContext) {
        this.mContext = mContext;
    }

    //把assets目录下的db文件复制到dbpath下
    public SQLiteDatabase initDBManager(String packName) {
        String dbPath = "/data/data/" + packName
                + "/databases/" + DB_NAME;
        if (!new File(dbPath).exists()) {
            try {
                FileOutputStream out = new FileOutputStream(dbPath);
                InputStream in = mContext.getAssets().open("cities.db");
                byte[] buffer = new byte[1024];
                int readBytes = 0;
                while ((readBytes = in.read(buffer)) != -1)
                    out.write(buffer, 0, readBytes);
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return SQLiteDatabase.openOrCreateDatabase(dbPath, null);
    }

    //查询
    public ArrayList<City> query(SQLiteDatabase sqliteDB, String[] columns, String selection, String[] selectionArgs) {
        City city = null;
        ArrayList<City> citylists = new ArrayList<City>();
        try {
            String table = "city";
            Cursor cursor = sqliteDB.rawQuery("select * FROM city", null);
            //   Cursor cursor = sqliteDB.query(table, null, null, null, null, null, null);
            //  cursor不为空，moveToFirst为true说明有数据
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    city = new City();
                    String name = cursor.getString(cursor.getColumnIndex("name"));
                    String pinyin = cursor.getString(cursor.getColumnIndex("pinyin"));
                    city.setName(name);
                    city.setPinyin(pinyin);
                    citylists.add(city);
                } while (cursor.moveToNext());
            }
            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return citylists;
    }
}
